import React from 'react'
import { Menu } from 'antd'
import { Link } from 'react-router-dom'
import { useSelector } from 'react-redux'
import { AppState } from '../store/reducers'
import { RouterState } from 'connected-react-router'
import { isAuth } from '../utils/auth'
import { Auth } from '../store/models/auth'

const NavBar = () => {
  const router = useSelector<AppState, RouterState>(state => state.router)

  const { pathname } = router.location

  function activeClass(path: string): string {
    return pathname === path ? 'ant-menu-item-selected' : ''
  }

  function dashboardMenu() {
    const {
      user: { role },
    } = isAuth() as Auth

    const path = role ? '/admin/dashboard' : '/user/dashboard'

    return (
      <Menu.Item key='/dashboard' className={activeClass(path)}>
        <Link to={path}>Dashboard</Link>
      </Menu.Item>
    )
  }

  return (
    <Menu mode='horizontal' selectable={false}>
      <Menu.Item key='/' className={activeClass('/')}>
        <Link to='/'>首页</Link>
      </Menu.Item>
      <Menu.Item key='/shop' className={activeClass('/shop')}>
        <Link to='/shop'>商城</Link>
      </Menu.Item>
      {isAuth() ? (
        dashboardMenu()
      ) : (
        <>
          <Menu.Item key='/signup' className={activeClass('/signup')}>
            <Link to='/signup'>注册</Link>
          </Menu.Item>
          <Menu.Item key='/signin' className={activeClass('/signin')}>
            <Link to='/signin'>登录</Link>
          </Menu.Item>
        </>
      )}
    </Menu>
  )
}

export default NavBar
